/**
 * 
 */
package com.jie.eclipse.pan.gef.listener;

import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.TableItem;

import com.jie.eclipse.pan.data.BaseDataEntities;
import com.jie.eclipse.pan.data.BaseDataEntity;
import com.jie.eclipse.pan.swtitem.table.PTableViewer;

/**
 * @author yanjie
 *
 */
public class PanTableOrderDropAdapter extends ViewerDropAdapter{
	/**
	 * @param viewer
	 */
	public PanTableOrderDropAdapter(Viewer viewer) {
		super(viewer);
	}

	private BaseDataEntity target = null;
	@Override
	public boolean validateDrop(Object paramObject, int paramInt,
			TransferData paramTransferData) {
		if(paramObject instanceof BaseDataEntity){
			target = (BaseDataEntity)paramObject;
			return true;
		}else{
			target = null;
			return true;
		}
		
	}
	
	@Override
	public boolean performDrop(Object paramObject) {
		if (paramObject != null && paramObject instanceof StructuredSelection) {
			StructuredSelection selection = (StructuredSelection) paramObject;
			if(selection.getFirstElement() != null && selection.getFirstElement() instanceof BaseDataEntity){
				BaseDataEntity source = (BaseDataEntity)selection.getFirstElement();
				PTableViewer tv = (PTableViewer)this.getViewer();
				BaseDataEntities rows = new BaseDataEntities();
				for (int i = 0; i < tv.getTable().getItems().length; i++) {
					TableItem item = tv.getTable().getItems()[i];
					if(item.getData() instanceof BaseDataEntity){
						BaseDataEntity tempdate = (BaseDataEntity)item.getData();
						if(tempdate == source){
							continue;
						}
						
						if(tempdate == target){
							rows.add(source);
							rows.add(target);
							continue;
						}
						rows.add(tempdate);
					}
				}
				tv.setInput(rows);
			} 
		}
		return true;
	}
}
